<template>
  <div class="heatmap-controls">
    <el-button type="primary" @click="toggleHeatmap" :disabled="loading">
      {{ isHeatmapVisible ? '隐藏热力图' : '显示热力图' }}
    </el-button>
    <div class="time-slider-container" v-if="isHeatmapVisible">
      <el-slider
        v-model="selectedYear"
        :min="minYear"
        :max="maxYear"
        :step="1"
        show-stops
        :marks="yearMarks"
        @change="switchHeatmap"
      />
    </div>
  </div>
</template>

<script>
import { ref, computed, defineProps } from 'vue';

export default {
  name: 'HeatmapComponent',
  props: {
    mapInstance: {
      type: Object,
      required: true
    }
  },
  setup(props) {
    const selectedYear = ref(2023);
    const years = [2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023];
    const currentLayer = ref(null);
    const isHeatmapVisible = ref(false);
    const loading = ref(false);

    const minYear = computed(() => Math.min(...years));
    const maxYear = computed(() => Math.max(...years));
    const yearMarks = computed(() => {
      const marks = {};
      years.forEach(year => {
        marks[year] = year.toString();
      });
      return marks;
    });

    const getBoundsFromPgw = async (year) => {
      const pgwUrl = `/HeatMap/${year}.pgw`;
      try {
        const response = await fetch(pgwUrl);
        if (!response.ok) throw new Error('无法加载 .pgw 文件');
        const text = await response.text();
        const lines = text.trim().split('\n').map(Number);
        if (lines.length !== 6 || lines.some(isNaN)) throw new Error('无效的 .pgw 文件格式');

        const [xRes, , , yRes, xMin, yMax] = lines;
        const img = new Image();
        img.src = `/HeatMap/${year}.png`;
        await new Promise(resolve => { img.onload = resolve; });
        const widthPx = img.width;
        const heightPx = img.height;
        const xMax = xMin + (xRes * widthPx);
        const yMin = yMax + (yRes * heightPx);

        return new window.AMap.Bounds(
          new window.AMap.LngLat(xMin, yMin),
          new window.AMap.LngLat(xMax, yMax)
        );
      } catch (error) {
        console.error(`读取 ${pgwUrl} 失败:`, error);
        return new window.AMap.Bounds(
          new window.AMap.LngLat(113.8, 30.2),
          new window.AMap.LngLat(114.8, 31.0)
        );
      }
    };

    const switchHeatmap = async () => {
      if (!isHeatmapVisible.value || !currentLayer.value) return;
      loading.value = true;
      try {
        props.mapInstance.remove(currentLayer.value);
        currentLayer.value = null;
        const heatmapUrl = `/HeatMap/${selectedYear.value}.png`;
        const bounds = await getBoundsFromPgw(selectedYear.value);
        currentLayer.value = new window.AMap.ImageLayer({
          url: heatmapUrl,
          bounds: bounds,
          opacity: 0.6,
          zooms: [5, 18]
        });
        currentLayer.value.setMap(props.mapInstance);
      } finally {
        loading.value = false;
      }
    };

    const toggleHeatmap = async () => {
      if (isHeatmapVisible.value) {
        if (currentLayer.value) {
          props.mapInstance.remove(currentLayer.value);
          currentLayer.value = null;
        }
        isHeatmapVisible.value = false;
      } else {
        loading.value = true;
        try {
          const heatmapUrl = `/HeatMap/${selectedYear.value}.png`;
          const bounds = await getBoundsFromPgw(selectedYear.value);
          currentLayer.value = new window.AMap.ImageLayer({
            url: heatmapUrl,
            bounds: bounds,
            opacity: 0.6,
            zooms: [5, 18]
          });
          currentLayer.value.setMap(props.mapInstance);
          isHeatmapVisible.value = true;
        } finally {
          loading.value = false;
        }
      }
    };

    return {
      selectedYear,
      years,
      minYear,
      maxYear,
      yearMarks,
      toggleHeatmap,
      isHeatmapVisible,
      loading,
      switchHeatmap
    };
  }
};
</script>

<style scoped>
/* 主容器调整 */
.heatmap-controls {
  display: inline-flex;
  position: relative;
  margin-left: 10px;
  vertical-align: middle;
}

/* 时间滑块容器调整 */
.time-slider-container {
  position: absolute;
  top: 45px;
  left: -100px; /* 改为右对齐 */
  width: 350px;
  background: rgba(255, 255, 255, 0.95);
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  z-index: 1000;
  border: 1px solid #ebeef5;
  animation: fadeIn 0.3s ease;
}

/* 在HeatmapComponent.vue的style中添加 */
:deep(.el-slider__marks-text) {
  transform: translateX(-50%);
  font-size: 11px;  /* 适当缩小字体 */
}

/* 特殊处理最后两个年份 */
:deep(.el-slider__marks-text:nth-last-child(1)) { /* 2023 */
  transform: translateX(0) !important;
  right: 2px;
  left: auto;
}

:deep(.el-slider__marks-text:nth-last-child(2)) { /* 2022 */
  transform: translateX(-70%) !important; /* 关键调整：左移20% */
  right: auto;
}

/* 滑块轨道调整 */
:deep(.el-slider__runway) {
  height: 6px;
  background-color: #f0f2f5;
  margin: 10px 0 15px;
  width: 95%; /* 减少宽度留出边距 */
  margin-left: 2.5%; /* 居中显示 */
}

/* 年份标记容器调整 */
:deep(.el-slider__marks) {
  width: 95%;
  margin-left: 2.5%;
}

/* 最后一个年份标记特殊处理 */
:deep(.el-slider__marks-text:last-child) {
  transform: translateX(0) !important; /* 取消偏移 */
  right: 0 !important;
  left: auto !important;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .time-slider-container {
    width: 300px;
    right: -50px; /* 小屏幕时向右偏移 */
  }

  :deep(.el-slider__marks-text) {
    font-size: 10px;
  }

  :deep(.el-slider__marks-text:last-child) {
    transform: translateX(10px) !important; /* 小屏幕额外右移 */
  }
}
</style>